<template>
  <div class="layout_card">
    <el-card>
      <el-form :inline="true" class="filter_section">
        <el-form-item label="用户名">
          <el-input placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="default">搜索</el-button>
          <el-button
            type="info"
            size="danger"
            @click="settingStore.refresh = !settingStore.refresh"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="" style="margin: 10px 0 0">
      <el-card>
        <div class="save_btns">
          <el-button
            type="primary"
            size="default"
            @click="OPEN_DIALOG()"
            v-has="'cuser.detail2'"
          >
            添加
          </el-button>
          <el-button
            size="danger"
            :disabled="DELETE_IDS ? false : true"
            @click="SELECT_DELETE_ATTR"
          >
            批量删除
          </el-button>
        </div>

        <div class="table_section" style="margin: 10px 0">
          <el-table
            :data="tableData"
            stripe
            border
            @selection-change="TABLE_SELECT_CALLBACK"
          >
            <el-table-column type="selection" align="center" />

            <el-table-column label="序号" width="100" type="index" />
            <el-table-column prop="id" label="id" width="100" />
            <el-table-column prop="username" label="用户姓名" width="150" />
            <el-table-column prop="name" label="用户昵称" width="150" />
            <el-table-column prop="roleName" label="用户角色" width="300" />
            <el-table-column prop="createTime" label="创建时间" width="200" />
            <el-table-column prop="updateTime" label="更新时间" width="200" />
            <el-table-column
              label="操作"
              fixed="right"
              width="280"
              align="center"
            >
              <template #default="{ row }">
                <el-button
                  type="primary"
                  icon="User"
                  size="small"
                  title="分配角色"
                  @click="OPEN_ROLE_DIALOG(row.id)"
                >
                  分配角色
                </el-button>

                <el-button
                  type="primary"
                  icon="Edit"
                  size="small"
                  title="编辑"
                  @click="OPEN_DIALOG(row.id)"
                >
                  编辑
                </el-button>

                <el-button
                  type="danger"
                  icon="Delete"
                  size="small"
                  title="删除"
                  @click="DELETE_ATTR(row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="pagination_section">
          <el-pagination
            v-model:current-page="form.pageNo"
            v-model:page-size="form.limit"
            :page-sizes="[10, 20, 50, 100]"
            background
            layout="prev, pager, next,jumper, ->,sizes,total "
            :total="total"
            @size-change="GET_LIST"
            @current-change="GET_LIST"
          />
        </div>
      </el-card>
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">
      <el-form :model="userData" ref="ruleFormRef" :rules="rules">
        <el-form-item label="用户姓名" prop="name">
          <el-input
            v-model="userData.name"
            placeholder="请输入用户姓名"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="username">
          <el-input
            v-model="userData.username"
            placeholder="请输入用户昵称"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            v-model="userData.password"
            placeholder="请输入用户密码"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="CLOSE_DIALOG">取消</el-button>
          <el-button type="primary" @click="ADDUPDATE_DIALOG">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="roleDialogVisible" title="分配角色" width="500">
      <el-form :model="userData">
        <el-form-item label="用户姓名">
          <el-input
            v-model="userData.name"
            placeholder="请输入用户姓名"
            autocomplete="off"
            disabled
          />
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="checkedRoles"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="role in roleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="CLOSE_ROLE_DIALOG">取消</el-button>
          <el-button type="primary" @click="EDIT_ROLE_DIALOG">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: 'userLayout',
}
</script>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules, CheckboxValueType } from 'element-plus'
import { onMounted, onBeforeUnmount, ref, reactive } from 'vue'
import { publicConfirm } from '@/utils/handleData'

import { reqAddOrUpdateTrademark, reqDeletTrademark } from '@/api/product'

import { resUserList, resRoleList } from '@/api/acl'
import type {} from '@/api/acl/type'
import useAttributeCate from '@/store/modules/attributeCateStore'
import useSettingStore from '@/store/modules/settingStore'

let AttributeCateStore = useAttributeCate()

let settingStore = useSettingStore()
onMounted(() => {
  GET_LIST()
})
onBeforeUnmount(() => {})

let total = ref<number>(1)
let form = reactive({
  pageNo: 1,
  limit: 10,
})
let tableData = ref<any>([])
let roleList = ref<any>([])

let DELETE_IDS = ref<string>('')

const dialogVisible = ref(false)
let dialogTitle = ref('')

const roleDialogVisible = ref(false)

const ruleFormRef = ref<FormInstance>()
const userData_init = {
  id: '',
  name: '',
  username: '',
  password: '',
  roleName: '',
}
let userData = reactive({ ...userData_init })

const GET_LIST = async () => {
  Object.assign(form, { category2Id: AttributeCateStore.key_third })
  let result: any = await resUserList(form)
  if (result.code == 200) {
    tableData.value = result.data.records
    total.value = result.data.total
  }
}

// 删除SPU
const DELETE_ATTR = async (id = 0) => {
  const flag = await publicConfirm({
    title: '提示',
    content: '确认删除该角色？',
  })
  let type = '删除'
  if (flag) {
    let result: any = await reqDeletTrademark(id)
    if (result.code == 200) {
      ElMessage({
        type: 'success',
        message: `${type}成功`,
      })
      GET_LIST()
    } else {
      ElMessage({
        type: 'error',
        message: `${type}失败`,
      })
    }
  } else {
    ElMessage({
      type: 'info',
      message: `取消${type}`,
    })
  }
}

const SELECT_DELETE_ATTR = async () => {
  const flag = await publicConfirm({
    title: '提示',
    content: '确认批量删除角色？',
  })
  let type = '删除'
  if (flag) {
    let result: any = await reqDeletTrademark(DELETE_IDS.value)
    if (result.code == 200) {
      ElMessage({
        type: 'success',
        message: `${type}成功`,
      })
      DELETE_IDS.value = ''
      window.location.reload()
    } else {
      ElMessage({
        type: 'error',
        message: `${type}失败`,
      })
    }
  } else {
    ElMessage({
      type: 'info',
      message: `取消${type}`,
    })
    DELETE_IDS.value = ''
    window.location.reload()
  }
}

const ADDUPDATE_DIALOG = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate()
  let result: any = await reqAddOrUpdateTrademark(userData)
  let type = '添加'
  if (userData.id) {
    type = '修改'
  }
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: `${type}成功`,
    })
    window.location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: `${type}成功`,
    })
  }
  CLOSE_DIALOG()
}
const OPEN_DIALOG = (id = 0) => {
  //   console.log(id)
  INIT_DIALOG()
  if (id > 0) {
    //修改
    dialogTitle.value = '编辑用户'
    const found = tableData.value.find((item) => item.id === id)
    if (found) {
      Object.assign(userData, found)
    }
  } else {
    // 添加
    dialogTitle.value = '添加用户'
  }
  dialogVisible.value = true
}

const INIT_DIALOG = () => {
  Object.assign(userData, userData_init)
  if (!ruleFormRef.value) return
  ruleFormRef.value.clearValidate('name')
  ruleFormRef.value.clearValidate('username')
  ruleFormRef.value.clearValidate('password')
}
const CLOSE_DIALOG = () => {
  dialogVisible.value = false
}

const rules = reactive<FormRules<any>>({
  name: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
})

const OPEN_ROLE_DIALOG = async (id = 0) => {
  await INIT_ROLE_DIALOG()
  const found = tableData.value.find((item) => item.id === id)
  if (found) {
    Object.assign(userData, found)
    if (userData.roleName) {
      checkedRoles.value = userData.roleName
        .split(',')
        .reduce((p: any[], n) => {
          let role = roleList.value.find((item) => item.roleName == n)
          //   console.log(role)
          p.push(role.id)
          return p
        }, [])
    }
  }
  roleDialogVisible.value = true
}
const INIT_ROLE_DIALOG = async () => {
  Object.assign(userData, userData_init)
  await GET_ROLE_LIST()
}
const GET_ROLE_LIST = async () => {
  Object.assign(form, { category2Id: AttributeCateStore.key_third })
  let result: any = await resRoleList(form)
  if (result.code == 200) {
    roleList.value = result.data.records
    allCheckedRoles.value = result.data.records.map((role) => role.id)
  }
}
const CLOSE_ROLE_DIALOG = () => {
  roleDialogVisible.value = false
}

const checkAll = ref(false)
const isIndeterminate = ref(true)

let checkedRoles = ref<any>([])
let allCheckedRoles = ref<any>([])

const handleCheckAllChange = (val: CheckboxValueType) => {
  checkedRoles.value = val ? allCheckedRoles.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: CheckboxValueType[]) => {
  console.log(value)
  const checkedCount = value.length
  checkAll.value = checkedCount === allCheckedRoles.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allCheckedRoles.value.length
}

const EDIT_ROLE_DIALOG = async () => {
  let result: any = await reqAddOrUpdateTrademark(userData)
  let type = '添加'
  if (userData.id) {
    type = '修改'
  }
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: `${type}成功`,
    })
  } else {
    ElMessage({
      type: 'error',
      message: `${type}成功`,
    })
  }
  CLOSE_ROLE_DIALOG()
}

const TABLE_SELECT_CALLBACK = (selects) => {
  DELETE_IDS.value = selects.map((item) => item.id).join(',')
}
</script>

<style scoped lang="scss">
.filter_section .el-input {
  --el-input-width: 220px;
}
.filter_section .el-input {
  --el-select-width: 220px;
}
</style>
